package org.example.fastJsonEnumSerializer;

import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.reader.ObjectReader;

import java.lang.reflect.Type;

public class EnumDeserializer implements ObjectReader<Object> {

    @Override
    public Object readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {
        return readObject(jsonReader, fieldType, fieldName, features, null, 0);
    }

    public <T> T readObject(
            JSONReader jsonReader,
            Type fieldType,
            Object fieldName,
            long features,
            Object defaultValue,
            int features2) {

        if (jsonReader.nextIfNull()) {
            return null;
        }

        Class<?> rawClass = (Class<?>) fieldType;

        // 类型安全检查
        if (!Enum.class.isAssignableFrom(rawClass) || !BaseEnum.class.isAssignableFrom(rawClass)) {
            throw new JSONException("Type must be an enum implementing BaseEnum");
        }

        // 读取值（自动处理不同类型）
        Object value = jsonReader.readAny();

        // 通过BaseEnum接口的反序列化方法
        @SuppressWarnings("unchecked")
        Class<? extends Enum<?>> enumClass = (Class<? extends Enum<?>>) rawClass;
        return (T) BaseEnum.fromValue((Class<? extends BaseEnum>) enumClass, value);

    }
}
